package com.mdb.open.epay.service.epay.handle;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mdb.bc.api.data.ListResultEx;
import com.mdb.bc.api.data.ResultEx;
import com.mdb.bc.api.enums.ApiEnum;
import com.mdb.bc.cache.MdbCache;
import com.mdb.bc.utils.BeanConvertUtil;
import com.mdb.bc.utils.ObjectUtil;
import com.mdb.open.epay.cache.CacheConfig;
import com.mdb.open.epay.config.EPayOpenProperties;
import com.mdb.open.epay.enums.type.HolidayFlagEnum;
import com.mdb.open.epay.feign.OutreachClient;
import com.mdb.open.epay.feign.dto.*;
import com.mdb.open.epay.service.epay.handle.dto.GetCoreAccountDto;
import com.mdb.open.epay.service.epay.handle.dto.GetCoreCustDto;
import com.mdb.open.epay.service.epay.handle.dto.GetCoreTranDto;
import com.mdb.open.epay.service.epay.handle.dto.QueryHolidayDto;
import com.mdb.open.epay.service.epay.handle.vo.CoreAccountVo;
import com.mdb.open.epay.service.epay.handle.vo.CoreCustVo;
import com.mdb.open.epay.service.epay.handle.vo.CoreTranVo;
import com.mdb.open.epay.service.epay.handle.vo.HolidayVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Log4j2
@Service
public class QueryCoreHandle {

    @Autowired
    private OutreachClient outreachClient;
    @Autowired
    private MdbCache mdbCache;
    @Autowired
    private EPayOpenProperties ePayOpenProperties;

    /**
     * 服務啟動獲取核心假期表，存入緩存
     */
    public ListResultEx<HolidayVo> getAndSetCoreHolidayToCache() {
        String valueStr = mdbCache.get(CacheConfig.CORE_HOLIDAY_KEY);
        if (ObjectUtil.isNotEmpty(valueStr)) {
            List<HolidayVo> cacheHolidayVo = JSONArray.parseArray(valueStr, HolidayVo.class);
            if (ObjectUtil.isNotEmpty(cacheHolidayVo)) {
                return ListResultEx.ok(cacheHolidayVo);
            }
        }
        //缓存失效，重新查询核心
        QueryHolidayDto queryHolidayDto = new QueryHolidayDto();
        queryHolidayDto.setCountry(ePayOpenProperties.getHolidayCountry());
        queryHolidayDto.setYear(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy")));
        ListResultEx<HolidayVo> holidayVoListResultEx = this.queryCoreHoliday(queryHolidayDto);
        if (holidayVoListResultEx.isFailed()) {
            return ListResultEx.fail();
        }
        List<HolidayVo> holidayVoList = holidayVoListResultEx.getData();

        //獲取明年假期表
        QueryHolidayDto queryNextYearHolidayDto = new QueryHolidayDto();
        queryNextYearHolidayDto.setCountry(ePayOpenProperties.getHolidayCountry());
        queryNextYearHolidayDto.setYear(LocalDate.now().plusYears(1).format(DateTimeFormatter.ofPattern("yyyy")));
        ListResultEx<HolidayVo> nextYearHolidayVoListResultEx = this.queryCoreHoliday(queryNextYearHolidayDto);

        //獲取後年假期表
        QueryHolidayDto queryNextNextYearHolidayDto = new QueryHolidayDto();
        queryNextNextYearHolidayDto.setCountry(ePayOpenProperties.getHolidayCountry());
        queryNextNextYearHolidayDto.setYear(LocalDate.now().plusYears(2).format(DateTimeFormatter.ofPattern("yyyy")));
        ListResultEx<HolidayVo> nextNextYearHolidayVoListResultEx = this.queryCoreHoliday(queryNextNextYearHolidayDto);

        if(nextYearHolidayVoListResultEx.isSuccess()){
            holidayVoList.addAll(nextYearHolidayVoListResultEx.getData());
        }
        if(nextNextYearHolidayVoListResultEx.isSuccess()){
            holidayVoList.addAll(nextNextYearHolidayVoListResultEx.getData());
        }

        List<HolidayVo> availHoliday = holidayVoList.stream()
                .filter(vo -> ApiEnum.parse(HolidayFlagEnum.class, vo.getHolidayFlag()) != null || !"0".equals(vo.getDate()))
                .collect(Collectors.toList());

        mdbCache.setEx(CacheConfig.CORE_HOLIDAY_KEY, JSON.toJSONString(availHoliday), ePayOpenProperties.getHolidayCacheTime(), TimeUnit.DAYS);
        return holidayVoListResultEx;
    }

    /**
     * 节假日查询 0359907
     */
    public ListResultEx<HolidayVo> queryCoreHoliday(QueryHolidayDto dto) {
        HST_0359907 requestDto = new HST_0359907();
        HST_0359907_Req hst_0359907_req = new HST_0359907_Req();
        hst_0359907_req.setCountry(dto.getCountry());
        hst_0359907_req.setYear(dto.getYear());
        hst_0359907_req.setDate(dto.getDate());
        requestDto.setBody(hst_0359907_req);

        ListResultEx<HST_0359907_Resp> coreResultEx = outreachClient.requestCoreApi0359907(requestDto);
        if (ObjectUtil.isEmpty(coreResultEx.getData())) {
            return ListResultEx.fail();
        }
        List<HolidayVo> voList = BeanConvertUtil.convertList(coreResultEx.getData(), hst_0359907_resp -> {
            HolidayVo holidayVo = new HolidayVo();
            holidayVo.setDate(hst_0359907_resp.getDate());
            holidayVo.setHolidayFlag(hst_0359907_resp.getHolidayFlag());
            return holidayVo;
        });
        return ListResultEx.ok(voList);
    }

    /**
     * 交易查证 0359902
     */
    public ResultEx<CoreTranVo> getCoreTran(GetCoreTranDto dto) {
        HST_0359902 requestDto = new HST_0359902();
        HST_0359902_Req hst_0359902_req = new HST_0359902_Req();
        hst_0359902_req.setInqFlg(dto.getInqFlg());
        hst_0359902_req.setAcDt(dto.getAcDt());
        hst_0359902_req.setJrnNo(dto.getJrnNo());
        hst_0359902_req.setReqSys(dto.getReqSys());
        hst_0359902_req.setExRef(dto.getExRef());
        requestDto.setBody(hst_0359902_req);

        ResultEx<HST_0359902_Resp> coreResultEx = outreachClient.requestCoreApi0359902(requestDto);
        if (coreResultEx.isFailed()) {
            return ResultEx.fail();
        }
        HST_0359902_Resp hst_0359902_resp = coreResultEx.getData();
        if (ObjectUtil.isEmpty(hst_0359902_resp)) {
            return ResultEx.ok();
        }
        CoreTranVo coreTranVo = new CoreTranVo();
        coreTranVo.setStatus(hst_0359902_resp.getStatus());
        coreTranVo.setJrnNo(hst_0359902_resp.getJrnNo());
        try {
            LocalDateTime acDt = LocalDate.parse(hst_0359902_resp.getAcDt(), DateTimeFormatter.ofPattern(DatePattern.PURE_DATE_PATTERN)).atStartOfDay();
            coreTranVo.setAcDt(acDt);
        } catch (Exception ex){

        }
        return ResultEx.ok(coreTranVo);
    }

    /**
     * 獲取核心客戶信息
     *
     * @param dto
     * @return
     */
    public ResultEx<CoreCustVo> getCoreCust(GetCoreCustDto dto) {

        HST_0350201 requestDto = new HST_0350201();
        HST_0350201_Req hst_0350201_req = new HST_0350201_Req();
        hst_0350201_req.setCiNo(dto.getCiNo());
        hst_0350201_req.setIdTyp(dto.getIdTyp());
        hst_0350201_req.setIdNo(dto.getIdNo());
        hst_0350201_req.setType(dto.getType());
        hst_0350201_req.setSeqno(dto.getSeqno());
        requestDto.setBody(hst_0350201_req);
        ResultEx<HST_0350201_Resp> coreResultEx = outreachClient.requestCoreApi0350201(requestDto);
        if (coreResultEx.isFailed()) {
            return ResultEx.fail();
        }
        HST_0350201_Resp hst_0350201_resp = coreResultEx.getData();
        if (ObjectUtil.isEmpty(hst_0350201_resp)) {
            return ResultEx.fail();
        }
        CoreCustVo coreCustVo = new CoreCustVo();
        coreCustVo.setCiNo(hst_0350201_resp.getCiNo());
        coreCustVo.setOicNo(hst_0350201_resp.getOicNo());
        coreCustVo.setOicBr(hst_0350201_resp.getOicBr());
        coreCustVo.setRegCty(hst_0350201_resp.getRegCty());
        coreCustVo.setEngName(hst_0350201_resp.getEngName());
        coreCustVo.setChnName(hst_0350201_resp.getChnName());
        coreCustVo.setCustType(hst_0350201_resp.getCustType());
        coreCustVo.setTelNo(hst_0350201_resp.getTelNo());
        coreCustVo.setFaxNo(hst_0350201_resp.getFaxNo());
        coreCustVo.setEmail(hst_0350201_resp.getEmail());
        coreCustVo.setEngAddr1(hst_0350201_resp.getEngAddr1());
        coreCustVo.setEngAddr2(hst_0350201_resp.getEngAddr2());
        coreCustVo.setEngAddr3(hst_0350201_resp.getEngAddr3());
        coreCustVo.setEngAddr4(hst_0350201_resp.getEngAddr4());
        coreCustVo.setLocTone(hst_0350201_resp.getLocTone());
        coreCustVo.setCommType(hst_0350201_resp.getCommType());
        coreCustVo.setSwiftCd(hst_0350201_resp.getSwiftCd());
        coreCustVo.setIntelType(hst_0350201_resp.getIntelType());
        coreCustVo.setIdType(hst_0350201_resp.getIdType());
        coreCustVo.setIdNo(hst_0350201_resp.getIdNo());
        coreCustVo.setIdType2(hst_0350201_resp.getIdType2());
        coreCustVo.setIdNo2(hst_0350201_resp.getIdNo2());
        coreCustVo.setLegalSts(hst_0350201_resp.getLegalSts());
        coreCustVo.setMobNo(hst_0350201_resp.getMobNo());
        coreCustVo.setDfltAddrFlg(hst_0350201_resp.getDfltAddrFlg());
        coreCustVo.setLocalAddr1(hst_0350201_resp.getLocalAddr1());
        coreCustVo.setLocalAddr2(hst_0350201_resp.getLocalAddr2());
        coreCustVo.setLocalAddr3(hst_0350201_resp.getLocalAddr3());
        coreCustVo.setLocalAddr4(hst_0350201_resp.getLocalAddr4());
        coreCustVo.setConTyp(hst_0350201_resp.getConTyp());
        coreCustVo.setLeaderCiNo(hst_0350201_resp.getLeaderCiNo());
        coreCustVo.setBankLcnsTp(hst_0350201_resp.getBankLcnsTp());
        coreCustVo.setCountry(hst_0350201_resp.getCountry());
        coreCustVo.setCntyCode(hst_0350201_resp.getCntyCode());
        coreCustVo.setSex(hst_0350201_resp.getSex());
        coreCustVo.setEngName1(hst_0350201_resp.getEngName1());
        coreCustVo.setLocalName(hst_0350201_resp.getLocalName());
        coreCustVo.setEaddrEmail(hst_0350201_resp.getEaddrEmail());
        coreCustVo.setEaddrTelNo(hst_0350201_resp.getEaddrTelNo());
        coreCustVo.setEaddrTelCntycd(hst_0350201_resp.getEaddrTelCntycd());
        coreCustVo.setEaddrTelCntyno(hst_0350201_resp.getEaddrTelCntyno());
        coreCustVo.setEaddrMobNo(hst_0350201_resp.getEaddrMobNo());
        coreCustVo.setEaddrMobCntycd(hst_0350201_resp.getEaddrMobCntycd());
        coreCustVo.setEaddrMobCntyno(hst_0350201_resp.getEaddrMobCntyno());
        coreCustVo.setEaddrFaxNo(hst_0350201_resp.getEaddrFaxNo());
        coreCustVo.setEaddrFaxCntycd(hst_0350201_resp.getEaddrFaxCntycd());
        coreCustVo.setEaddrFaxCntyno(hst_0350201_resp.getEaddrFaxCntyno());
        coreCustVo.setPromFlag(hst_0350201_resp.getPromFlag());
        coreCustVo.setSeqNo(hst_0350201_resp.getSeqNo());
        coreCustVo.setLists(hst_0350201_resp.getLists());
        return ResultEx.ok(coreCustVo);
    }

    /**
     * 獲取核心客戶的賬戶信息
     *
     * @param dto
     * @return
     */
    public ResultEx<CoreAccountVo> getCoreAccount(GetCoreAccountDto dto) {
        HST_0350202 requestDto = new HST_0350202();
        HST_0350202_Req hst_0350202_req = new HST_0350202_Req();
        hst_0350202_req.setCiNo(dto.getCiNo());
        hst_0350202_req.setCtl1(dto.getCtl1());
        hst_0350202_req.setCtl2(dto.getCtl2());
        hst_0350202_req.setIdType(dto.getIdType());
        hst_0350202_req.setIdNo(dto.getIdNo());
        requestDto.setBody(hst_0350202_req);
        ResultEx<HST_0350202_Resp> coreResultEx = outreachClient.requestCoreApi0350202(requestDto);
        if (coreResultEx.isFailed()) {
            return ResultEx.fail();
        }
        HST_0350202_Resp hst_0350202_resp = coreResultEx.getData();
        if (ObjectUtil.isEmpty(hst_0350202_resp)) {
            return ResultEx.fail();
        }

        CoreAccountVo coreAccountVo = new CoreAccountVo();
        coreAccountVo.setCiNo(hst_0350202_resp.getCiNo());
        coreAccountVo.setQactCnt(hst_0350202_resp.getQactCnt());
        coreAccountVo.setLists(hst_0350202_resp.getLists());

        return ResultEx.ok(coreAccountVo);
    }
}
